[Kotlin] - Pair
Pairλ
Pair
λ, ν μ;λ λΆλΆμ΄ ν¨κ» λΆμ΄ νλλ₯Ό μ΄λ£¨λ κ²μ μλ―Ένλ€.
kotlin
μμλ λμΌνκ² μμ μλ―Ένλ ν΄λμ€μ΄λ©°, ν΄λμ€ κ΅¬μ‘°λ μλμ κ°μ΄ μκ²Όλ€.
public data class Pair<out A, out B>(
public val first: A,
public val second: B
) : Serializable
μμΈν λ΄μ©μ 곡μ λ¬Έμλ₯Ό μ°Έκ³ νλ©΄ μ’μ κ² κ°λ€.
Pairμ μ¬μ©
μμ μ€λͺ ν κ²κ³Ό κ°μ΄ 2κ°μ λ³μλ₯Ό λ¬Άμ΄μ μ¬μ©ν μ μμΌλ©°, μ΄λ ν νμ μ΄λ λ£μ μ μλ€.
λ°μ΄ν° μ μ₯
μλ μ½λμ κ°μ΄ λ€μν λ°©λ²μΌλ‘ μ μκ° κ°λ₯νλ€.
var a = Pair(1, "짱ꡬ")
val b = Pair<Int, String>(second = "μ² μ", first = 2)
val (c1, c2) = Pair(3, "μ 리")
val (d1, d2) = 4 to "νλ°λ‘¬"
μ½κ° μμν μ½λκ° μλ€λ©΄ c1
, c2
λ³μλ₯Ό κ΄νΈλ‘ λ¬Άμ΄ μ¬μ©νλ κ²μ΄λ€.
Pair
κ° ν μμ μλ―Ένλ κ²μ²λΌ ν μμ λ³μλ‘ λ¬Άμ΄μ μ¬μ©νλ κ²μ΄λ€.
λ°μ΄ν° μΆλ ₯
μΆλ ₯μ Pair
μ 첫 λΆλΆμ μ¬μ©νκ³ μΆλ€λ©΄ first
λ₯Ό νΈμΆνκ³ , λ λ²μ§Έ λΆλΆμ μ¬μ©νκ³ μΆλ€λ©΄ second
λ₯Ό νΈμΆνλ©΄ λλ€.
println("a.first = ${a.first} \t a.second = ${a.second}")
println("a = $a")
println("c.first = $c1 \t c.second = $c2")
// a.first = 1 a.second = 짱ꡬ
println("a.first = ${a.first} \t a.second = ${a.second}")
// a = (1, 짱ꡬ)
println("a = $a")
// b.first = 2 b.second = μ² μ
println("b.first = ${b.first} \t b.second = ${b.second}")
// b = (2, μ² μ)
println("b = $b")
// c.first = 3 c.second = μ 리
println("c.first = $c1 \t c.second = $c2")
// d.first = 4 d.second = νλ°λ‘¬
println("d.first = $d1 \t d.second = $d2")
λ°μ΄ν° μμ
μμ ν΄λμ€ κ΅¬μ‘°λ₯Ό 보면 μλ―μ΄ val
λ‘ λμ΄ μμ΄μ λ°μ΄ν°λ₯Ό μμ ν μ μλ€.
κ·ΈλΌμλ κΌ μμ μ΄ νμν κ²½μ° copy
λ₯Ό ν΅ν΄ λ€μ ν λΉνλ λ°©μμΌλ‘ ν μ μλ€.
a = a.copy(first = 5, second = "λ")
λ°μ΄ν° μ λ ¬
Pair
λ λ€λ₯Έ ν΄λμ€μ λ€λ₯΄κ² PriorityQueue
λ₯Ό ν΅ν΄ μ λ ¬ν μ μλ€.
fun main() {
val pq = PriorityQueue<Pair<Int, Int>>()
pq.offer(1 to 1)
pq.offer(2 to 2)
while (!pq.isEmpty()) {
val cur = pq.poll()
println(cur.first)
}
}
μμ κ°μ΄ μμ±νλ©΄ μ»΄νμΌ νμμλ μλ¬λ λμ§ μμ§λ§, λ°νμμμ μλμ κ°μ μλ¬κ° λ°μνλ€.
Exception in thread "main" java.lang.ClassCastException:
class kotlin.Pair cannot be cast to class java.lang.Comparable
(kotlin.Pair is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
μλ¬ λ΄μ©μ μ΄ν΄λ³΄λ©΄ Pair
ν΄λμ€λ Comparable
λ‘ μΊμ€νΈν μ μλ€λ λ΄μ©μ΄λ€.
μ¦, Comparable
μ ꡬννμ§ μμ 무μκ³Ό λΉκ΅λ₯Ό ν΄μ μ λ ¬ν μ§ μ μλμ΄ μμ§ μλ€λ κ²μ΄λ€.
μ΄λ₯Ό ν΄κ²°νλ λ°©λ²μ μκ°λ³΄λ€ κ°λ¨νλ€.
// λ°©μ 1
val pq = PriorityQueue<Pair<Int, Int>>(Comparator() { a, b -> a.first - b.first })
// λ°©μ 2
val pq = PriorityQueue<Pair<Int, Int>> { a, b -> a.first - b.first }
μμ κ°μ΄ Comparator
λ₯Ό μ κ³΅ν΄ μ λ ¬μ ν΄μ£Όλ©΄ λλ€.
λκΈλ¨κΈ°κΈ°